<template>
  <div class="message-sider">
    <n-scrollbar>
      <div
        class="list-item"
        v-for="item in contactList"
        :key="item.uid"
        @click="changeContact(item)"
        :style="{
          'background-color': isUidEqual(item.uid, contactUid) ? '#eee' : ''
        }"
      >
        <n-avatar round :src="item.avatar" class="avatar" />
        <div class="right">
          <div class="item-name">{{ item.name }}</div>
          <div class="msg">{{ item.content }}</div>
        </div>
      </div>
    </n-scrollbar>
  </div>
  <div class="message-window" v-if="props.target != 0">
    <div class="name">{{ contactName }}</div>
    <div class="chat pt-1 overflow-auto" ref="chat">
      <template v-if="message.length === 0 && contentLoading">
        <div class="flex p-4">
          <n-skeleton circle class="!w-10 !h-10 shrink-0"></n-skeleton>
          <n-skeleton class="!h-10 ml-2 !w-64" round></n-skeleton>
        </div>
        <div class="flex p-4 justify-end">
          <n-skeleton class="!h-10 !w-64" round></n-skeleton>
          <n-skeleton circle class="!w-10 ml-2 !h-10 shrink-0"></n-skeleton>
        </div>
      </template>
      <div class="chat-box" v-for="(item, index) in message" :key="index">
        <div v-if="item.type == 1" class="chat-left">
          <div class="chat-avatar">
            <n-avatar round :src="item.avatar" />
          </div>
          <div class="chat-content-left">
            {{ item.content }}
          </div>
        </div>
        <div v-else class="chat-right">
          <n-icon
            style="vertical-align: super; margin-right: 3px"
            v-if="item.error"
            color="#e11010"
          >
            <AlertCircle />
          </n-icon>
          <div class="chat-content-right">
            {{ item.content }}
          </div>
          <div class="chat-avatar">
            <n-avatar round :src="item.avatar" />
          </div>
        </div>
      </div>
    </div>
    <div class="input">
      <n-input
        :disabled="contentLoading"
        type="textarea"
        class="write"
        placeholder="在这里发消息哦"
        v-model:value="sendMsg"
        :bordered="false"
        @keyup.enter="send"
        autosize
      >
      </n-input>
      <div class="snd">
        <n-button type="primary" @click="send" size="small">发送</n-button>
      </div>
    </div>
  </div>
  <div class="message-window gap-10 p-10" v-else>
    <n-skeleton text :repeat="5"></n-skeleton>
    <n-skeleton text style="width: 60%" />
  </div>
</template>

<script setup>
import { AlertCircle } from '@vicons/ionicons5'
import api from '@/api/api'
const { Message, User } = api

const props = defineProps({
  //目标用户
  target: {
    default: '0'
  }
})

const chat = ref(null)

const scrollToEnd = (smooth = true) => {
  nextTick(() => {
    chat.value.scrollTo({
      top: chat.value.scrollHeight,
      behavior: smooth ? 'smooth' : 'auto'
    })
  })
}

watch(
  () => {
    return props.target
  },
  () => {
    console.log('change')
    //当目标聊天用户变化时触发
    contactUid.value = props.target
    getName()
  }
)

const contactList = ref([])

const getContact = () => {
  Message.getContact({}).then((res) => {
    if (res.success) {
      contactList.value = res.list
      if (props.target === '0') {
        if (contactList.value.length !== 0)
          router.push(String(contactList.value[0].uid))
      } else {
        getName()
      }
    }
  })
}
const isUidEqual = (a, b) => {
  return decodeURIComponent(a) === decodeURIComponent(b)
}
// 通过当前聊天的用户id获取用户详细信息
const getName = () => {
  if (contactUid.value == 0) return
  // 是否有目标聊天用户
  if (
    !contactList.value.some((item) => {
      return isUidEqual(item.uid, props.target)
    })
  ) {
    addContact()
  }
  User.getProfile({
    id: contactUid.value
  }).then((res) => {
    if (res.success) {
      contactName.value = res.data.name
      contactAvatar.value = res.data.avatar
      getContent()
    } else {
      router.push('/message/chat/0')
    }
  })
}
// 将路由中新添加的用户id添加到联系人列表
const addContact = () => {
  Message.addContact({
    uid: props.target
  })
    .then((res) => {
      if (res.success) {
        contactList.value.unshift({
          uid: props.target,
          avatar: contactAvatar.value,
          name: contactName.value,
          content: message.value.length
            ? message.value[message.value.length - 1].content
            : ''
        })
        getContent()
      }
    })
    .catch(() => {
      router.push('/message/chat/0')
    })
}
onMounted(() => {
  getMyName()
  getContact()
})

//window
const message = ref([])
const contactUid = ref(props.target)
// 现在交流的人的名字
const contactName = ref('')
const contactAvatar = ref('')

const contentLoading = ref(true)
const getContent = () => {
  contentLoading.value = true
  Message.getContent({
    contact: contactUid.value
  }).then((res) => {
    contentLoading.value = false
    if (res.success) {
      message.value = res.list
      scrollToEnd(false)
    }
  })
}

const router = useRouter()

function changeContact(item) {
  const { uid, name, avatar } = item
  if (uid === contactUid.value) return
  router.push(String(uid))
  contactUid.value = uid
  contactName.value = name
  contactAvatar.value = avatar
  message.value = []
  // getContent()
}

const sendMsg = ref('')
const myInfo = ref({
  name: '',
  avatar:
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-ab00bb59ac5dadfa1d898370ce8199e8_r.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664713010&t=7d08068e645885082d044b778d2eccd1'
})

const getMyName = () => {
  // Message.getName({
  //   uid: store.state.userInfo.userId
  // }).then((res) => {
  //   if (res.success) {
  //     myInfo.value.name = res.data.name
  //     // myInfo.value.avatar = res.data.avatar;
  //   }
  // })
  User.getProfile({
    id: localStorage.getItem('id')
  }).then((res) => {
    if (res.success) {
      myInfo.value = res.data
    }
  })
}
const sendMessage = () => {
  const saveMsg = sendMsg.value
  sendMsg.value = ''
  Message.sendMessage({
    contact: contactUid.value,
    content: saveMsg
  })
    .then((res) => {
      if (!res.success) {
        message.value.at(-1).error = true
      } else {
        const findContact = contactList.value.find((item) => {
          return isUidEqual(item.uid, contactUid.value)
        })
        if (findContact) findContact.content = saveMsg
      }
    })
    .catch((e) => {
      console.log(e)
      message.value.at(-1).error = true
    })
  scrollToEnd()
}

// const a = ref({uid: 1})

const send = () => {
  if (!sendMsg.value) return
  message.value.push({
    content: sendMsg.value,
    type: 0,
    time: '',
    avatar: myInfo.value.avatar
  })
  sendMessage()
}

onMounted(() => {
  initWebSocket()
})
onUnmounted(() => {
  websocketclose(websock)
})

// websocket
let websock
function initWebSocket() {
  const id = localStorage.getItem('id')
  //初始化weosocket
  const wsuri = 'ws://39.105.128.207:8000/message/link/' + id //ws地址
  websock = new WebSocket(wsuri)
  websock.onopen = websocketonopen
  websock.onerror = websocketonerror
  websock.onmessage = websocketonmessage
  websock.onclose = websocketclose
}

function websocketonopen() {
  console.log('WebSocket连接成功')
}
function websocketonerror(e) {
  //错误
  console.log('WebSocket连接发生错误')
}
function websocketonmessage(e) {
  //数据接收
  console.log(e)
  let data = JSON.parse(e.data)
  console.log(data)
  // update list
  const tmpContactInList = contactList.value.find((item) =>
    isUidEqual(item.uid, data.sender_id)
  )
  if (tmpContactInList) tmpContactInList.content = data.content
  // update current chat
  if (isUidEqual(data.sender_id, contactUid.value)) {
    message.value.push({
      content: data.content,
      type: 1,
      time: data.time,
      avatar: data.sender_avatar
    })
    scrollToEnd()
  }

  // switch (data.messageType) {
  //   case 'send':
  //     if (data.receiveId === store.state.userInfo.userId) {
  //       if (data.sendUid === props.target) {
  //         message.value.push({
  //           content: data.content,
  //           type: 1,
  //           time: '',
  //           avatar: contactAvatar.value
  //         })
  //         scrollToEnd()
  //       }
  //     }
  //     break
  //   case 'at':
  //     break
  //   case 'subscribe':
  //     break
  //   case 'reply':
  //     break
  // }
}

function websocketsend(agentData) {
  //数据发送
  websock.send(agentData)
}

function websocketclose(e) {
  //关闭
  console.log('connection closed (' + e.code + ')')
}
</script>

<style scoped lang="scss">
// @media screen and (max-width: 768px) {
//   .message-sider {
//     width: 80px !important;
//     padding: 0 !important;
//   }
//   .list-item {
//     width: 60px !important;
//     margin-left: 10px;
//   }
// }
//sider
.message-sider {
  background-color: #fff;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  width: 240px;
  height: calc(100vh - 170px);
}
.list-item {
  padding: 0 15px;
  cursor: pointer;
  position: relative;
  width: 200px;
  height: 70px;
  transition: 0.2s;
  &:hover {
    background-color: #f5f5f5;
  }
}
.avatar {
  display: inline-block;
  position: absolute;
  transform: translate(0, -50%);
  top: 50%;
  width: 3.5em;
  height: 3.5em;
}
.right {
  display: inline-block;
  position: absolute;
  transform: translate(0, -50%);
  top: 50%;
  left: 75px;
  text-align: left;
  width: 120px;
}
.item-name {
  font-size: 1rem;
  line-height: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.msg {
  margin-top: 5px;
  font-size: 0.8rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
}
//window

.message-window {
  width: 100%;
  height: calc(100vh - 170px);
  background-color: #f4f5f7;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  display: flex;
  flex-direction: column;

  .name {
    background-color: #fefefe;
    border-top-right-radius: 5px;
    font-size: 20px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .chat {
    height: calc(100% - 150px);
  }
  .input {
    height: 100px;
    border-top: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
  }
  .write {
    background: transparent;
    width: 100%;
    height: 50px;
    resize: none;
    border: none;
    outline: none;
  }
  .snd {
    height: 20px;
    line-height: 20px;
    align-self: flex-end;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.chat-box {
  margin: 5px 0;
}
.chat-left {
  margin-left: 20px;
}
.chat-right {
  margin-right: 20px;
  text-align: right;
}
.chat-avatar {
  vertical-align: top;
  display: inline-block;
}
.chat-content-left {
  background-color: #eee;
  margin-left: 10px;
  max-width: 30%;
  display: inline-block;
  border-radius: 0 10px 10px 10px;
  padding: 5px;
  overflow: hidden;
  white-space: normal;
  word-break: break-all;
}

.chat-content-right {
  background-color: #eee !important;
  margin-right: 10px;
  max-width: 30%;
  display: inline-block;
  border-radius: 10px 0px 10px 10px;
  padding: 5px;
  overflow: hidden;
  white-space: normal;
  word-break: break-all;
  text-align: left;
}
// .n-divider:not(.n-divider--vertical) {
//   margin-top: 0 !important;
//   margin-bottom: 10px !important;
// }
</style>
